# coding=utf-8

from flask import current_app,Blueprint,request,jsonify,make_response
from xlrd import open_workbook
import os
from utils.myf import myf
from io import BytesIO
from xlrd import open_workbook
from urllib.parse import quote
import xlsxwriter
import datetime
import mimetypes
from utils.mydb import db1
from utils.xtree import xtree
from utils.xdata import xdata
from utils.getdata import getdata
from utils.myes import Es
import json
from utils.myredis import r
from utils.mytoken import token1

user_bp = Blueprint("user_bp",__name__)

@user_bp.route("/worklist")
def worklist():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})

@user_bp.route("/getsource")
def getsource():
    values = r.str_get("datasource")
    if values:
        lst = eval(values)
    else:
        sql = "select * from data_source"
        res = db1.find_all(sql)
        lst = []
        if res:
            for i in res:
                dic = {"id":i["id"],"name":i["name"]}
                msql = "select id,name,type from %s"%i["tablename"]
                mres = db1.find_all(msql)
                dic["mes"] = mres
                lst.append(dic)
        r.str_set("datasource",json.dumps(lst))

    return jsonify({"code":200,"list":lst})

@user_bp.route('/addworkflow',methods=["POST"])
def addworkflow():
    data = getdata()
    sql = "select * from workflow where id=%d"%int(data["id"])
    res = db1.find(sql)
    if res:
        # print(json.loads(data["list"]))
        # data["list"] = json.loads(data["list"])
        # for i in data["list"]:
        #     i["value"]=json.loads(i["value"])
        # print(data["list"])
        usql = "update workflow set params='%s' where id=%d"%(str(data["list"]),int(res["id"]))
        db1.update(usql)
    return jsonify({"code":200,"msg":"修改成功"})

# 查询工作流
@user_bp.route("/query_workflow")
def query_workflow():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})


@user_bp.route('/addtask',methods=["POST"])
def addtask():
    data = getdata()
    title = str(json.loads(data["params"])["姓名"]+data["title"])
    sql = "insert into task(title,params,status,user_id) values('%s','%s',0,%d)"%(title,data["params"],int(data["userid"]))
    db1.update(sql)
    return jsonify({"code":200,"msg":"添加成功"})

@user_bp.route("/menu_auth")
def menu_auth():
    userid = request.args.get("userid")
    sql = "select r.id,r.name,r.url,pr.name as pname,pr.id as pid from user_resource as ur left join resources as r on ur.resource_id=r.id left join resources as pr on r.pid=pr.id where user_id=%d and pr.type=1"%int(userid)
    res = db1.find_all(sql)
    list = xdata(res)
    return jsonify({"code":200,"list":list})


